/**
 * 
 */
package cn.gov.msa.controller;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;

import cn.gov.msa.collection.LdapService;
import cn.gov.msa.dao.AmanuensisMapper;
import cn.gov.msa.dao.ApplyMapper;
import cn.gov.msa.dao.ApplyMaterialMapper;
import cn.gov.msa.dao.DeclareItemMapper;
import cn.gov.msa.dao.FlowBusinessMapper;
import cn.gov.msa.dao.FlowInstanceMapper;
import cn.gov.msa.dao.FlowNodeMapper;
import cn.gov.msa.dao.FlowNodeParamMapper;
import cn.gov.msa.dao.FlowTaskMapper;
import cn.gov.msa.dao.FlowTaskUserMapper;
import cn.gov.msa.dao.OrgMapper;
import cn.gov.msa.dao.UserDetailMapper;
import cn.gov.msa.model.Amanuensis;
import cn.gov.msa.model.Apply;
import cn.gov.msa.model.ApplyMaterial;
import cn.gov.msa.model.AuditOpinion;
import cn.gov.msa.model.BaseObj;
import cn.gov.msa.model.DeclareItem;
import cn.gov.msa.model.Flow;
import cn.gov.msa.model.FlowBusiness;
import cn.gov.msa.model.FlowInstance;
import cn.gov.msa.model.FlowNextNode;
import cn.gov.msa.model.FlowNextNodeE;
import cn.gov.msa.model.FlowNode;
import cn.gov.msa.model.FlowNodeParam;
import cn.gov.msa.model.FlowTask;
import cn.gov.msa.model.FlowTaskUser;
import cn.gov.msa.model.FlowTaskUserE;
import cn.gov.msa.model.RecordCompany;
import cn.gov.msa.model.UserDetail;
import cn.gov.msa.model.UserRole;
import cn.gov.msa.service.ApplyService;
import cn.gov.msa.service.DeclareItemService;
import cn.gov.msa.service.FlowService;
import cn.gov.msa.service.SmsLogService;
import cn.gov.msa.service.TaskService;
import cn.gov.msa.service.UserDetailService;
import cn.gov.msa.util.ESSPDFClientToolUtil;
import cn.gov.msa.util.InfoObjUtil;
import cn.gov.msa.util.PropertiesTools;
import cn.gov.msa.util.SmsTools;
import cn.gov.msa.ws.BusinessService;
import cn.gov.msa.ws.ConsultingService;
import cn.gov.msa.ws.DeclareServcie;
import cn.gov.msa.ws.DictService;
import cn.gov.msa.ws.FileService;
import cn.gov.msa.ws.NoticeServcie;
import cn.gov.msa.ws.OrgService;
import cn.gov.msa.ws.QuestionService;
import cn.gov.msa.ws.RepositoryService;
import cn.gov.msa.ws.ReserveService;
import cn.gov.msa.ws.SystemService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

/**
 * @author 何宇江
 * 2018-2-28
 *
 */

@RestController
@RequestMapping(value = "/flow", produces="text/plain;charset=UTF-8")
public class FlowController {

	ObjectMapper mapper = new ObjectMapper(); 	
	@Autowired
	TaskService taskService;
	@Autowired
	FlowService flowService;
	@Autowired
	ApplyService applyService;
	@Autowired
	ApplyMapper applyMapper;
	@Autowired
	SmsLogService smsLogService;
	@Autowired
	FlowNodeParamMapper flowNodeParamMapper;
	@Autowired
	FlowNodeMapper flowNodeMapper;
	@Autowired
	UserDetailMapper userDetailMapper;
	@Autowired
	FlowTaskUserMapper flowTaskUserMapper;
	@Autowired
	FlowTaskMapper flowTaskMapper;
	@Autowired
	FlowInstanceMapper flowInstanceMapper;
	@Autowired
	OrgMapper orgMapper;

	private static String url = PropertiesTools.readProperties("project.url");
	private static String path = PropertiesTools.readProperties("project.path");
	
	@RequestMapping(value = "/list")
	public String list(@RequestBody JSONObject params) throws Exception {
		String result = "";
		
//		BaseObj ss = new BaseObj();
//		String nam = ss.getName();
		
		int pageNum = 1;
		int pageSize = 10;
		if(params.has("pageNum"))
		{
			pageNum = params.getInt("pageNum");
			params.remove("pageNum");
		}
		if(params.has("pageSize"))
		{
			pageSize = params.getInt("pageSize");
			params.remove("pageSize");
		}
		

		Flow flow = mapper.readValue(params.toString(), Flow.class);
		
		
		List<Flow> flowList = flowService.selectData(pageNum, pageSize, flow);
	    //获取分页信息
        PageInfo page = new PageInfo(flowList);
        

		JSONArray ja = JSONArray.fromObject(flowList);
		
		
		JSONObject jsonResult = new JSONObject();
		jsonResult.put("total", page.getTotal());
		jsonResult.put("rows", ja);
		
		
		result = jsonResult.toString();
		return result;
	}
	
	

	@RequestMapping(value = "/save")
	public String save(@RequestBody JSONObject param) throws Exception{	
		String result = "0";
		String info = InfoObjUtil.Error_save_no;
	    JSONObject jsonResult = new JSONObject();
	    
		
	    try{
		    String flownumber = "";
	    	if(param.has("flownumber"))
	    		flownumber = param.getString("flownumber");
		    
		    
			//得到节点的model数据
			JSONArray jaDetail = param.getJSONObject("table").getJSONArray("row");
			List<FlowNode> flowNodeList = new ArrayList<FlowNode>();
			for (Object detailObject : jaDetail) {
				FlowNode flowNode = mapper.readValue(detailObject.toString(), FlowNode.class);
				flowNode.setFlownumber(flownumber);
				flowNodeList.add(flowNode);
			}
			
			//得到流程的model数据
			param.remove("table");
			Flow flow = mapper.readValue(param.toString(), Flow.class);	
		    
			boolean save = flowService.save(flow, flowNodeList, null);
		    
		    if(save){
		    	result = "1";
		    	info = InfoObjUtil.Success_save_OK;
		    }
	    }
	    catch(Exception e){
			e.printStackTrace();
	    	result = "2";
	    	info = InfoObjUtil.Exption_msg;
	    }
	    

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);
	    
		return jsonResult.toString();
	}


	@RequestMapping(value = "/savejointlysign")
	public String savejoinlysign(@RequestBody JSONObject param,HttpSession session) throws Exception{	
		int result = 1;
		String info = InfoObjUtil.Success_save_OK;;
	    String userID = session.getAttribute("userid").toString();
	    UserDetail userDetail=(UserDetail) session.getAttribute("userDetail");
	    try{
	    	FlowNode flowNodeQueryParam=new FlowNode();
	    	flowNodeQueryParam.setFlownumber("N41");
	    	List<FlowNode> flowNodeList=flowNodeMapper.selectData(flowNodeQueryParam);//先找出流程所有的
//    		JSONArray gTasks=new JSONArray();
	    	for (int i = 0; i < param.getJSONArray("userData").size(); i++) {//每人一个新流程
	    		JSONObject userData=param.getJSONArray("userData").getJSONObject(i);
	    		FlowInstance flowInstance = new FlowInstance();
	    		String instanceid = UUID.randomUUID().toString().toUpperCase();
	    		flowInstance.setInstanceid(instanceid);
	    		flowInstance.setFlownumber("N41");
	    		flowInstance.setBusinessid(param.getString("applyid"));//TODO
	    		flowInstance.setPflowtaskid(param.getString("flowtaskid"));//TODO
	    		flowInstance.setPinstanceid(param.getString("instanceid"));//TODO
	    		for (int j = 0; j < flowNodeList.size(); j++) {//根据之前的流程代码，每个流程启动，都会直接新建所有的task出来
	    			if(j==0){
						FlowTask flowTask = new FlowTask();
						String taskid = UUID.randomUUID().toString().toUpperCase();
						flowTask.setTaskid(taskid);
						flowTask.setInstanceid(instanceid);
						flowTask.setSerialnumber(flowNodeList.get(j).getSerialnumber());
						flowTask.setNodecode(flowNodeList.get(j).getNodecode());
						flowTask.setTaskname(flowNodeList.get(j).getNodename());
						flowTask.setSendtime(new Date());
						flowTask.setSenduserid(userID);//记录谁发过来的
						flowTask.setSendusername(userDetail.getUsername());
						flowTask.setTaskstate(0);
						flowTask.setTaskurl("backstage/approval/business/jointlysignaccept.html");
						flowInstance.setFlowtaskid(taskid);//目前是到这一步
						flowTaskMapper.insert(flowTask);
						
						FlowTaskUser flowTaskUser = new FlowTaskUser();
						flowTaskUser.setSerialnumber(1); 
						flowTaskUser.setTaskid(taskid);
						flowTaskUser.setUserid(userData.getString("userid"));
						flowTaskUser.setUsername(userData.getString("username"));
						flowTaskUser.setOrgcode(userData.getString("orgcode"));
//						flowTaskUser.setDeptcode(userData.getString("deptcode"));
						flowTaskUser.setHandleproposal(userData.optString("handleproposal"));
						flowTaskUserMapper.insert(flowTaskUser);
						
//						JSONObject gTask=new JSONObject();
//						gTask.put("userId", flowTaskUser.getUserid());
//						gTask.put("appId", PropertiesTools.readProperties("project.appId"));
//						gTask.put("appName",  PropertiesTools.readProperties("project.appName"));
//						gTask.put("status", flowNodeList.get(j).getNodecode());
//						gTask.put("statusName", flowNodeList.get(j).getNodename());
//						gTask.put("currentNodeId", flowNodeList.get(j).getNodecode());
//						gTask.put("currentNodeName", flowNodeList.get(j).getNodename());
//						gTask.put("appTaskId", flowTaskUser.getTaskuserid());//taskUserId作为4A中的taskId
//						gTask.put("taskName", param.getString("applyno")+"-"+param.getString("itemname")+"-会签");
//						String urlSuffix= URLEncoder.encode("applyid="+param.getString("applyid")+"&applyno="+param.getString("applyno")+"&pinstanceid="+param.getString("instanceid")+"&jointlysign=1"+"&instanceid="+instanceid+"&flowtaskid="+taskid+"&taskuserid="+ flowTaskUser.getTaskuserid()+"&itemname="+param.optString("itemname")+"&taskname="+flowNodeList.get(j).getNodename()+"&orgname="+param.optString("orgname"),"UTF-8");
//						gTask.put("taskURL", url+"/backstage/approval/business/accept4a.html?"+urlSuffix);
//						gTask.put("isDone", "0");
//						gTask.put("accessPlatform", "0");
//						gTask.put("businessType",PropertiesTools.readProperties("project.businessType"));
//						gTasks.add(gTask);
					}else {
						FlowTask flowTask = new FlowTask();
						String taskid = UUID.randomUUID().toString().toUpperCase();
						flowTask.setTaskid(taskid);
						flowTask.setInstanceid(instanceid);
						flowTask.setSerialnumber(flowNodeList.get(j).getSerialnumber());
						flowTask.setNodecode(flowNodeList.get(j).getNodecode());
						flowTask.setTaskname(flowNodeList.get(j).getNodename());
						flowTask.setSenduserid(userID);//记录谁发过来的
						flowTask.setSendusername(userDetail.getUsername());
						flowTask.setTaskstate(0);
						flowTaskMapper.insert(flowTask);
					}
				}
	    		flowInstanceMapper.insert(flowInstance);
	    	}
	    	System.out.println("4A任务指派");
//	    	System.out.println(gTasks);
//			System.out.println(taskService.gTaskBatchAdd(gTasks));
	    }
	    catch(Exception e){
			e.printStackTrace();
	    	result = 2;
	    	info = InfoObjUtil.Exption_msg;
	    }
	    JSONObject jsonResult = new JSONObject();
    	jsonResult.put("result", result);
    	jsonResult.put("info", info);	    
		return jsonResult.toString();
	}
	
	@RequestMapping(value = "/savenextnode")
	public String saveNextnode(@RequestBody JSONObject param) throws Exception{	
		int result = 0;
		String info = "";
	    boolean save = false; 
	    
	    System.err.println(param);
		
	    try{
			save = flowService.saveNextNode(param);
	    }
	    catch(Exception e){
			e.printStackTrace();
	    	result = 2;
	    	info = InfoObjUtil.Exption_msg;
	    }
	    
	    
	    JSONObject jsonResult = new JSONObject();
	    if(save){
	    	result = 1;
	    	info = InfoObjUtil.Success_save_OK;
	    }
	    else{
	    	result = 0;
	    	info = InfoObjUtil.Error_save_no;
	    }
	    

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);
	    
		return jsonResult.toString();
	}


	@RequestMapping(value = "/delete")
	public String delete(String flownumber) throws Exception{	

		int result = 0;
		String info = "";
	    boolean save = false; 
	    
		
	    try{
		    save = flowService.delete(flownumber);
	    }
	    catch(Exception e){
			e.printStackTrace();
	    	result = 2;
	    	info = InfoObjUtil.Exption_msg;
	    }
	    
	    
	    JSONObject jsonResult = new JSONObject();
	    if(save){
	    	result = 1;
	    	info = InfoObjUtil.Success_save_OK;
	    }
	    else{
	    	result = 0;
	    	info = InfoObjUtil.Error_save_no;
	    }
	    

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);
	    
		return jsonResult.toString();
	}
	
	

	@RequestMapping(value = "/getnodes")
	public String getnodes(String flownumber, String businessnumber) throws Exception{	
		int result = 0;
		String info = "";
		String datas = "";
		List<FlowNode> flowNodeList = null;
		List<FlowNodeParam> flowNodeParamList = null;
	    
		
	    JSONObject jsonResult = new JSONObject();
	    try{
	    	JSONArray jaResult = new JSONArray();
	    	if(null != businessnumber && "" != businessnumber){
	    		flowNodeParamList = flowNodeParamMapper.selectByBusinessnumber(businessnumber);
	    	
	    		jaResult = JSONArray.fromObject(flowNodeParamList);
	    	}
	    	
	    	if(jaResult.size() == 0){
	    		flowNodeList = flowService.getNodes(flownumber);
	    	
	    		jaResult = JSONArray.fromObject(flowNodeList);
	    	}
	    	datas = jaResult.toString();
	    }
	    catch(Exception e){
			e.printStackTrace();
	    	result = 2;
	    	info = InfoObjUtil.Exption_msg;
	    }
	    
	    
	    if((flowNodeList !=null && flowNodeList.size() > 0) || (flowNodeParamList !=null && flowNodeParamList.size() > 0)){
	    	result = 1;
	    	info = InfoObjUtil.Success_select_OK;

	    	jsonResult.put("datas", datas);
	    }
	    else{
	    	result = 0;
	    	info = InfoObjUtil.Error_NODATA;
	    }
	    

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);
	    
		return jsonResult.toString();
	}
	


	@RequestMapping(value = "/getnextnodes")
	public String getnextnodes(String nodecode) throws Exception{	
		int result = 0;
		String info = "";
		String datas = "";
		List<FlowNextNodeE> flowNextNodeList = null;
	    
		
	    try{
	    	flowNextNodeList = flowService.getNextNodes(nodecode);
	    	
	    	datas = JSONArray.fromObject(flowNextNodeList).toString();
	    	System.err.println(datas);
	    }
	    catch(Exception e){
			e.printStackTrace();
	    	result = 2;
	    	info = InfoObjUtil.Exption_msg;
	    }
	    
	    
	    JSONObject jsonResult = new JSONObject();
	    if(flowNextNodeList !=null && flowNextNodeList.size() > 0){
	    	result = 1;
	    	info = InfoObjUtil.Success_select_OK;

	    	jsonResult.put("datas", datas);
	    }
	    else{
	    	result = 0;
	    	info = InfoObjUtil.Error_NODATA;
	    }
	    

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);
	    
		return jsonResult.toString();
	}
	
	@Autowired
	AmanuensisMapper amanuensisMapper;
	@Autowired
	DeclareItemService declareItemService;
	@Autowired
	private DeclareItemMapper declareItemMapper;

	@RequestMapping(value = "/saveflowbusiness")
	public String saveflowbusiness(@RequestBody JSONObject param) throws Exception{	
		int result = 0;
		String info = "";
	    boolean save = false; 
	    
		
	    try{
	    	String businessnumber = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
	    	
			//得到节点参数的model数据
			JSONArray jaNodeParam = param.getJSONArray("FlowNodeParam");
			List<FlowNodeParam> flowNodeParamList = new ArrayList<FlowNodeParam>();
			for (Object flowNodeParamObject : jaNodeParam) {
				FlowNodeParam flowNodeParam = mapper.readValue(flowNodeParamObject.toString(), FlowNodeParam.class);
				flowNodeParam.setBusinessnumber(businessnumber);
				flowNodeParamList.add(flowNodeParam);
			}
			
			System.err.println(param.getJSONObject("FlowBusiness").toString());
			//得到流程业务的model数据
			FlowBusiness flowBusiness = mapper.readValue(param.getJSONObject("FlowBusiness").toString(), FlowBusiness.class);	
			flowBusiness.setBusinessnumber(businessnumber);
			
		    save = flowService.saveFlowBusiness(flowBusiness, flowNodeParamList);
		    

			String itemno = flowBusiness.getProjectno();
			DeclareItem declareItem = declareItemService.getInfoByItemno(itemno);
			declareItem.setApproveflow(businessnumber);
			int i = declareItemMapper.updateByPrimaryKey(declareItem);
			
			System.err.println(i);
			
	    }
	    catch(Exception e){
			e.printStackTrace();
	    	result = 2;
	    	info = InfoObjUtil.Exption_msg;
	    }
	    
	    
	    JSONObject jsonResult = new JSONObject();
	    if(save){
	    	result = 1;
	    	info = InfoObjUtil.Success_save_OK;
	    }
	    else{
	    	result = 0;
	    	info = InfoObjUtil.Error_save_no;
	    }
	    

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);
	    
		return jsonResult.toString();
	}
	

	@Autowired
	FlowBusinessMapper flowBusinessMapper;

	@RequestMapping(value = "/getFlowBusinessInfo")
	public String getFlowBusinessInfo(String businessnumber) throws Exception{	
		int result = 0;
		String info = "";
		String datas = "";
	    JSONObject jsonResult = new JSONObject();
		
	    try{
	    	FlowBusiness flowBusiness = flowBusinessMapper.selectByPrimaryKey(businessnumber);
	    	
	    	datas = JSONArray.fromObject(flowBusiness).toString();

		    if(flowBusiness != null){
		    	result = 1;
		    	info = InfoObjUtil.Success_select_OK;

		    	jsonResult.put("datas", datas);
		    }
		    else{
		    	result = 0;
		    	info = InfoObjUtil.Error_NODATA;
		    }
		    
	    }
	    catch(Exception e){
			e.printStackTrace();
	    	result = 2;
	    	info = InfoObjUtil.Exption_msg;
	    }
	    
	    

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);
	    
		return jsonResult.toString();
	}
	

	
	
	
	@RequestMapping(value = "/getuserbynodecode")
	public String getUserByNodecode(String businessid, String nodecode, String itemno, String orgcode) throws Exception{	
		int result = 0;
		String info = "";
		String datas = "";
	    JSONObject jsonResult = new JSONObject();
    	JSONArray jaUser = new JSONArray();
		
    	System.err.println(">>>>>>>>>" + businessid);
    	
	    try{
	    	FlowNode flowNode = flowNodeMapper.selectByPrimaryKey(nodecode);
//	    	String returnnodecode = flowNode.getReturnnodecode();
	    	
	    	String rolecodes = "";
	    	List<FlowNodeParam> flowNodeParamList = flowNodeParamMapper.selectByItemno(itemno);
	    	for (FlowNodeParam flowNodeParam : flowNodeParamList) {
//				if(flowNodeParam.getNodecode().equals(nodecode) || flowNodeParam.getNodecode().equals(returnnodecode)){
				if(flowNodeParam.getNodename().contains("补正")){
					FlowTaskUserE flowTaskUserE = new FlowTaskUserE();
					flowTaskUserE.setBusinessid(businessid);
					if(!flowNode.getNodename().contains("补正"))
						flowTaskUserE.setNodecode(flowNodeParam.getNodecode());
					List<FlowTaskUser> flowTaskUserList = flowTaskUserMapper.selectReturnUser(flowTaskUserE);
					for (FlowTaskUser flowTaskUser : flowTaskUserList) {
						jaUser.add(flowTaskUser);
					}
				}
				if(flowNodeParam.getNodecode().equals(nodecode)){
					rolecodes = flowNodeParam.getRolecode();
				}
			}
	    	
	    	if(null != rolecodes && "" != rolecodes){
		    	for (String rolecode : rolecodes.split(",")) {
		    		JSONArray ja = new JSONArray();
		    		if("1".equals(PropertiesTools.readProperties("sys.isintegration"))){
		    			ja = LdapService.getUserByRoleCode(rolecode, orgMapper.select4aByOrgCode(orgcode).getOrgCode4A());
		    		} else {
			    		UserRole userRole = new UserRole();
			    		userRole.setRolecode(rolecode);
			    		userRole.setOrgcode(orgcode);
			    		List<UserRole> userRoleList =  userDetailMapper.selectUserRole(userRole);
		
			    		ja = JSONArray.fromObject(userRoleList);
		    			
		    		}
		    		
		    		for (Object object : ja) {
						JSONObject user1 = JSONObject.fromObject(object);
						boolean b = true;
						
						for (Object object2 : jaUser) {
							JSONObject user = JSONObject.fromObject(object2);
							if(user.getString("userid") == user1.getString("userid")){
								b = false;
								break;
							}
						}
						
						if(b)
							jaUser.add(object);
					}
				}
	    	}
	    	datas = jaUser.toString();
	    	

		    
		    if(jaUser.size() > 0){
		    	result = 1;
		    	info = InfoObjUtil.Success_select_OK;

		    	jsonResult.put("datas", datas);
		    }
		    else{
		    	result = 0;
		    	info = InfoObjUtil.Error_NODATA;
		    }
	    }
	    catch(Exception e){
			e.printStackTrace();
	    	result = 2;
	    	info = InfoObjUtil.Exption_msg;
	    }
	    
	    

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);
	    
		return jsonResult.toString();
	}
	
	@Autowired
	ApplyMaterialMapper applyMaterialMapper;

	@RequestMapping(value = "/auditopinion")
	public String auditOpinion(@RequestBody JSONObject params) throws Exception{	
		int result = 0;
		String info = "";
		String datas = "";
	    JSONObject jsonResult = new JSONObject();
		
	    try{
	    	
	    	System.err.println(params);
//			String userID = session.getAttribute("userid").toString();
			
//	    	System.err.println(userID);
	    	
	    	JSONObject jsonAuditOpinion = params.getJSONObject("auditopinion");
	    	JSONArray jaUsers = params.getJSONArray("users");
	    	JSONArray annexids = params.optJSONArray("annexids");
//	    	保存意见表信息
	    	AuditOpinion auditOpinion = (AuditOpinion)JSONObject.toBean(jsonAuditOpinion, AuditOpinion.class);
	    	auditOpinion.setOrgcode(auditOpinion.getSysorg());
	    	auditOpinion.setUserid(auditOpinion.getSyscreatedby());
	    	auditOpinion.setUsername(auditOpinion.getSyscreatedbyname());
	    	auditOpinion.setInstanceid(auditOpinion.getInstanceid());
	    	auditOpinion.setTaskid(auditOpinion.getTaskid());
	    	auditOpinion.setSerialnumber(1);
	    	Apply apply = applyMapper.selectByPrimaryKey(jsonAuditOpinion.getString("businessid"));
	    	List<FlowTaskUser> flowTaskUserList = new ArrayList<FlowTaskUser>();
	    	int i = 1;
	    	for (Object userO : jaUsers) {
				JSONObject jsonUser = JSONObject.fromObject(userO);
				FlowTaskUser flowTaskUser = (FlowTaskUser)JSONObject.toBean(jsonUser, FlowTaskUser.class);
				
				flowTaskUserList.add(flowTaskUser);
				i++;
			}

	    	if(params.has("correction")){
		    	JSONArray jaCorrection = params.getJSONArray("correction");
		    	int k =0;
		    	for (Object object : jaCorrection) {
					JSONObject jsonApplyMaterial = JSONObject.fromObject(object);
					ApplyMaterial applyMaterial = (ApplyMaterial)JSONObject.toBean(jsonApplyMaterial, ApplyMaterial.class);
					applyMaterial.setIscorrection(1);
					k = applyMaterialMapper.updateByPrimaryKeySelective(applyMaterial);
				}
	    	}
	    	FlowNode nextflownode = flowNodeMapper.selectByPrimaryKey(auditOpinion.getNextnodecode());
	    	
	    	boolean save = flowService.saveAuditOpinion(auditOpinion,flowTaskUserList,annexids,nextflownode,jsonAuditOpinion.getString("taskuserid"),apply.getItemno(),apply.getApplyno(),apply.getProposerid(),apply.getItemname(),apply.getOrgname());
	    	
		    if(save){ 	
		    	
		    	String nodename=apply.getNodename();
		    	String nextnodename=nextflownode.getNodename();
		    	System.out.println(nextnodename);
		    	System.out.println(nodename);
		    	switch(nodename) {
			    	//系统业务
					case "发证":				// 业务查询
						Amanuensis amanuensis = new Amanuensis();
						amanuensis.setApplyid(auditOpinion.getBusinessid());
						amanuensis.setAmanuensiscode("03");
						List<Amanuensis> amanuensisList = amanuensisMapper.selectData(amanuensis);
						for (int j = 0; j < amanuensisList.size(); j++) {
							String oldPath=path + amanuensisList.get(j).getFileurl();
							String newPath=path + amanuensisList.get(j).getFileurl();
							String ruleNum="5FCD78A0D158CA63";
							//签章
							/*boolean signResult=ESSPDFClientToolUtil.pdfSign(ruleNum, oldPath, newPath);
							if(signResult) {//签章后更新数据库文件
								Amanuensis updateAmanuensis = new Amanuensis();
								File file = new File(newPath);
								amanuensis.setAttachment(FileCopyUtils.copyToByteArray(file));
								updateAmanuensis.setAmanuensisid(amanuensisList.get(j).getAmanuensisid());
								updateAmanuensis.setAttachment(FileCopyUtils.copyToByteArray(file));
								amanuensisMapper.updateByPrimaryKeySelective(updateAmanuensis);
								System.out.println("签章成功");
							}	*/					
						}
					break;
		    	}
		    	
		    	String smsContent=null;
		    	switch (nextnodename) { //发短信
					case "业务审核":				
						smsContent="您申报的业务已受理";
						break;					
					case "办结（不予受理）":			
						smsContent="您申报的业务不予受理";
						break;	
					case "材料补正":			
						smsContent="您申报的业务需要补正材料";
						break;	
					case "办结（不予许可）":					
						smsContent="您申报的业务不予许可";
						break;	
					case "办结":			
						smsContent="您申报的业务已办结";
						break;	
					default:
						break;
		    	} 
		    	/*if(!StringUtils.isEmpty(smsContent)&&!StringUtils.isEmpty(apply.getMobilephone())) {
		    		try {
						SmsTools.sendMsg(apply.getMobilephone(), smsContent,smsLogService);
					} catch (Exception e) {
						e.printStackTrace();
					}
		    	}*/
		    	
		    	
		    	
		    	
	        	boolean b = applyService.saveAmanuensis(apply.getApplyno(), null);
		    	
		    	result = 1;
		    	info = InfoObjUtil.Success_save_OK;

		    	jsonResult.put("datas", datas);
		    }
		    else{
		    	result = 0;
		    	info = InfoObjUtil.Error_save_no;
		    }
	    }
	    catch(Exception e){
			e.printStackTrace();
	    	result = 2;
	    	info = InfoObjUtil.Exption_msg;
	    }
	    
	    

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);
	    
		return jsonResult.toString();
	}
	
	
	
	@RequestMapping(value = "/jointlysignaccept")
	public String jointlysignaccept(@RequestBody JSONObject params) throws Exception{	
		int result = 1;
		String info = InfoObjUtil.Success_save_OK;
	    JSONObject jsonResult = new JSONObject();	
	    try{
	    	
	    	System.err.println(params);
	    	JSONObject jsonAuditOpinion = params.getJSONObject("auditopinion");
	    	JSONArray jaUsers = params.getJSONArray("users");
	    	JSONArray annexids = params.optJSONArray("annexids");
//	    	保存意见表信息
	    	JsonConfig config = new JsonConfig();  
			config.setExcludes(new String[]{//只要设置这个数组，指定过滤哪些字段。     
	          "taskuserid"  
	        });    
			config.setRootClass(AuditOpinion.class);
	    	
	    	AuditOpinion auditOpinion = (AuditOpinion)JSONObject.toBean(JSONObject.fromObject(jsonAuditOpinion,config), AuditOpinion.class);
	    	auditOpinion.setOrgcode(auditOpinion.getSysorg());
	    	auditOpinion.setUserid(auditOpinion.getSyscreatedby());
	    	auditOpinion.setUsername(auditOpinion.getSyscreatedbyname());
	    	auditOpinion.setInstanceid(auditOpinion.getInstanceid());
	    	auditOpinion.setTaskid(auditOpinion.getTaskid());
	    	auditOpinion.setSerialnumber(1);
	    	List<FlowTaskUser> flowTaskUserList = new ArrayList<FlowTaskUser>();
	    	for (Object userO : jaUsers) {
				JSONObject jsonUser = JSONObject.fromObject(userO);
				FlowTaskUser flowTaskUser = (FlowTaskUser)JSONObject.toBean(jsonUser, FlowTaskUser.class);
				flowTaskUserList.add(flowTaskUser);
			}
	    	flowService.saveJointlySignOpinion(auditOpinion,flowTaskUserList,annexids,jsonAuditOpinion.getString("taskuserid"));    
	    }
	    catch(Exception e){
			e.printStackTrace();
	    	result = 2;
	    	info = InfoObjUtil.Exption_msg;
	    }
    	jsonResult.put("result", result);
    	jsonResult.put("info", info);
	    
		return jsonResult.toString();
	}
	
	
	

	@RequestMapping(value = "/getnodeparaminfo")
	public String getNodeParamInfo(String itemno, String nodecode) throws Exception{	
		int result = 0;
		String info = "";
		String datas = "";
	    JSONObject jsonResult = new JSONObject();
		
	    try{
	    	List<FlowNodeParam> flowNodeParamList = flowNodeParamMapper.selectByItemno(itemno);
	    	
	    	FlowNodeParam flowNodeParam = null;
	    	for (FlowNodeParam flowNodeParam1 : flowNodeParamList) {
				if(nodecode.equals(flowNodeParam1.getNodecode())){
					flowNodeParam = flowNodeParam1;
					break;
				}
			}

		    if(flowNodeParam != null){
		    	result = 1;
		    	info = InfoObjUtil.Success_select_OK;

		    	jsonResult.put("datas", flowNodeParam);
		    }
		    else{
		    	result = 0;
		    	info = InfoObjUtil.Error_NODATA;
		    }
		    
	    }
	    catch(Exception e){
			e.printStackTrace();
	    	result = 2;
	    	info = InfoObjUtil.Exption_msg;
	    }
	    
	    

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);
	    
		return jsonResult.toString();
	}
	
	
	@RequestMapping(value = "/getFlowTaskInfo")
	public String getFlowTaskInfo(String flowtaskid) throws Exception{	
		int result = 0;
		String info = "";
		String datas = "";
	    JSONObject jsonResult = new JSONObject();
		
	    try{
	    	FlowTask flowTask = flowTaskMapper.selectByPrimaryKey(flowtaskid);
	    	
	    	datas = JSONObject.fromObject(flowTask).toString();

		    if(flowTask != null){
		    	result = 1;
		    	info = InfoObjUtil.Success_select_OK;

		    	jsonResult.put("datas", datas);
		    }
		    else{
		    	result = 0;
		    	info = InfoObjUtil.Error_NODATA;
		    }
		    
	    }
	    catch(Exception e){
			e.printStackTrace();
	    	result = 2;
	    	info = InfoObjUtil.Exption_msg;
	    }
	    
	    

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);
	    
		return jsonResult.toString();
	}
	
	
	@RequestMapping(value = "/queryflowtask")
	public String queryflowtaskbyinstanceid(@RequestBody JSONObject param) throws Exception{	
		int result = 0;
		String info = "";
	    JSONObject jsonResult = new JSONObject();	
	    try{
	    	FlowTask flowTaskParam=(FlowTask) JSONObject.toBean(param, FlowTask.class);
	    	JSONArray flowTaskResult = JSONArray.fromObject(flowTaskMapper.selectData(flowTaskParam));
		    if(flowTaskResult != null&&!flowTaskResult.isEmpty()){
		    	result = 1;
		    	info = InfoObjUtil.Success_select_OK;
		    	jsonResult.put("datas", flowTaskResult);
		    }
		    else{
		    	result = 0;
		    	info = InfoObjUtil.Error_NODATA;
		    }    
	    }
	    catch(Exception e){
			e.printStackTrace();
	    	result = 2;
	    	info = InfoObjUtil.Exption_msg;
	    }
    	jsonResult.put("result", result);
    	jsonResult.put("info", info);
		return jsonResult.toString();
	}
	
	//校验会签流程是否完毕
	@RequestMapping(value = "/checkjointlysign")
	public String checkjointlysign(@RequestBody JSONObject param) throws Exception{	
		int result = 0;
		String info = "";
	    JSONObject jsonResult = new JSONObject();	
	    try{
	    	
	    	JSONArray flowTaskResult = flowTaskMapper.selectjointlysigntask(param);
		    if(flowTaskResult != null&&!flowTaskResult.isEmpty()){
		    	result = 1;
		    	info = InfoObjUtil.Success_select_OK;
		    	jsonResult.put("datas", flowTaskResult);
		    }
		    else{
		    	result = 0;
		    	info = InfoObjUtil.Error_NODATA;
		    }    
	    }
	    catch(Exception e){
			e.printStackTrace();
	    	result = 2;
	    	info = InfoObjUtil.Exption_msg;
	    }
    	jsonResult.put("result", result);
    	jsonResult.put("info", info);
		return jsonResult.toString();
	}
	
	//查询一个流程里面的会签节点
	@RequestMapping(value = "/selectjointlysignnode")
	public String selectjointlysignnode(@RequestBody JSONObject param) throws Exception{	
		int result = 0;
		String info = "";
	    JSONObject jsonResult = new JSONObject();	
	    try{ 	
	    	JSONArray nodeResult = flowNodeParamMapper.selectjointlysignnodeparam(param);
		    if(nodeResult != null&&!nodeResult.isEmpty()){
		    	result = 1;
		    	info = InfoObjUtil.Success_select_OK;
		    	jsonResult.put("datas", nodeResult);
		    }
		    else{
		    	result = 0;
		    	info = InfoObjUtil.Error_NODATA;
		    }    
	    }
	    catch(Exception e){
			e.printStackTrace();
	    	result = 2;
	    	info = InfoObjUtil.Exption_msg;
	    }
    	jsonResult.put("result", result);
    	jsonResult.put("info", info);
		return jsonResult.toString();
	}
	@RequestMapping(value = "/selecttaskuser")
	public String selecttaskuser(@RequestBody JSONObject param) throws Exception{	
	    FlowTaskUser flowTaskUser=flowTaskUserMapper.selectByPrimaryKey(param.getString("taskuserid"));
		return JSONObject.fromObject(flowTaskUser).toString();
	}
}
